package com.demo.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.DecimalFormat;

import javax.servlet.http.HttpServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

import com.demo.javabean.UserBean;

public class UserServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String method = (String)request.getParameter("method");
		if(method==null) {
			PrintWriter out = response.getWriter();
			out.println("invalid request!");
		} else if(method.equals("login")) {
			Login(request, response);
		} else if(method.equals("logout")) {
			Logout(request, response);
		} else if(method.equals("testdb")) {
			TestDB(request, response);
		} else if(method.equals("register")) {
			Register(request, response);
		} else if(method.equals("download")) {
			Download(request, response);
		}
	}
	
	protected void TestDB(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		UserBean userBean = new UserBean();
		userBean.testDB();
	}

	protected void Login(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// get parameters
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		// check null
		if (username == null || password == null) {
			response.sendRedirect("traffichub.jsp");
			return;
		}

		// validate
		UserBean userBean = new UserBean();
		boolean isValid = userBean.valid(username, password);
		
		if (isValid) 
		{
			HttpSession session = request.getSession();
			session.setAttribute("username", username);
			
			// get user's real time latitude and longitude, read from the database
			String userLat = userBean.Lat(username);
			String userLon = userBean.Lon(username);
			
			// to regular decimal format with "0.000" (string - double -string)
			DecimalFormat df = new DecimalFormat("0.0000000"); 
			String userlat = df.format(Double.parseDouble(userLat)).toString();
			String userlon = df.format(Double.parseDouble(userLon)).toString();
			
			session.setAttribute("userlon",userlon);
			session.setAttribute("userlat",userlat);		

			response.sendRedirect("traffichublogin.jsp");
			return;
		} 
		else 
		{
			response.sendRedirect("traffichub.jsp");
			return;
		}
	}

	protected void Logout(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		session.removeAttribute("username");
		response.sendRedirect("traffichub.jsp");
	}
	
	@SuppressWarnings("static-access")
	protected void Download(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		String pathsavefile="D:\\Users\\ZHU RUI\\workspace\\ZRTrafficWeb\\WebContent\\ZRTraffic.apk";
		String fileName="ZRTraffic App.apk";
		try
		{
			response.reset();
			response.setContentType("APPLICATION/OCTET-STREAM");
			fileName=response.encodeURL(new String(fileName.getBytes(),"ISO8859_1"));
			response.setHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"");
			
			ServletOutputStream out = response.getOutputStream();
			InputStream inStream=new FileInputStream(pathsavefile);
			
			byte[] b = new byte[1024];

			int len;
			while((len=inStream.read(b)) >0)
				out.write(b,0,len);

			response.setStatus( response.SC_OK );
			response.flushBuffer();
			out.close();
			inStream.close();
		}
		catch (Exception e)
		{
			System.out.println(e);
		}
	}

	protected void Register(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// get parameters
		String username = request.getParameter("username");
		String password1 = request.getParameter("password1");
		String password2 = request.getParameter("password2");
		String lat = request.getParameter("lat");
		String lon = request.getParameter("lon");

		// check null
		if (username == null || password1 == null || password2 == null || !password1.equals(password2)) {
			response.sendRedirect("register.jsp");
			return;
		}

		// validate
		UserBean userBean = new UserBean();
		boolean isExist = userBean.isExist(username);
		if(!isExist) {
			userBean.add(username, password1,lat,lon);
			response.sendRedirect("traffichub.jsp");
			return;
		} else {
			response.sendRedirect("register.jsp");
			return;
		}
	}

	//Servlet listener
	public class MyHttpSessionAttributeListener implements HttpSessionAttributeListener
    {  
	    //session
	    public void attributeAdded(HttpSessionBindingEvent se) {  
	        System.out.println("Add session attribution, attName:" + se.getName() + ",attValue:" + se.getValue());  
	    }  
	    //session
	    public void attributeRemoved(HttpSessionBindingEvent se) {  
	        System.out.println("Delete session attribution:" + se.getName());  
	    }  
	    //session
	    public void attributeReplaced(HttpSessionBindingEvent se) {  
	        System.out.println("Replace session attribution:" + se.getName());  
	    }  
	}//end of Servlet listener
}






